const app = getApp();

Page({
  data: {
    productId: 'PSnackPickup',
    schoolCode: '', // 学校代码
    subProductInitInfo: null, // 页面初始化信息
    curSelectedBuilding: null, // 当前选中的楼栋
    subProductList: [], // 商品列表
    displayStockMap: {}, // 展示用库存（扣减购物车数量后的剩余）
    showBuildingModal: false, // 是否显示楼栋选择弹窗
    buildingSearchKey: '', // 楼栋搜索关键词
    filteredBuildings: [], // 过滤后的楼栋列表
    shoppingCart: {}, // 当前楼栋购物车 {subProductId: {product, count}}
    showCartModal: false, // 是否显示购物车弹窗
    totalPrice: 0, // 总价
    totalCount: 0, // 总数量
    openId: ''
  },

  onLoad(options) {
    wx.showLoading({ title: '加载中' });
    console.log('buildingSnacksStore.onLoad.start', options);
    
    // 获取schoolCode参数
    const schoolCode = options.schoolCode;
    if (!schoolCode) {
      wx.showToast({
        title: '缺少学校参数',
        icon: 'error'
      });
      wx.navigateBack();
      return;
    }
    
    // 获取openId
    const openId = wx.getStorageSync('openId') || app.globalData.openId || '';
    this.setData({ 
      openId,
      schoolCode 
    });
    
    this.initPage();
  },

  onShow() {
    console.log('buildingSnacksStore.onShow');
  },

  // 页面初始化
  initPage() {
    // 调用api getSubProductPageInfo
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getSubProductPageInfoRequest: {
          productId: this.data.productId,
          schoolCode: this.data.schoolCode
        }
      },
      success: (res) => {
        console.log('getSubProductPageInfo result:', res);
        if (res.result?.code === 200) {
          const subProductInitInfo = res.result.data;
          this.setData({
            subProductInitInfo,
            filteredBuildings: subProductInitInfo.buildings || []
          });

          // 检查是否有选中的楼栋
          const cachedBuilding = wx.getStorageSync('curSelectedBuilding');
          if (cachedBuilding && cachedBuilding.productId === this.data.productId) {
            // 从服务器数据中获取最新的楼栋信息，确保noticeBanner是最新的
            const latestBuilding = subProductInitInfo.buildings.find(b => 
              b.buildingCode === cachedBuilding.building.buildingCode
            );
            if (latestBuilding) {
              this.setData({
                curSelectedBuilding: latestBuilding
              });
              // 更新缓存为最新数据
              wx.setStorageSync('curSelectedBuilding', {
                productId: this.data.productId,
                building: latestBuilding
              });
            } else {
              this.setData({
                curSelectedBuilding: cachedBuilding.building
              });
            }
            // 加载该楼栋的购物车
            this.loadCartForCurrentBuilding();
            this.loadSubProductList();
          } else {
            // 显示楼栋选择弹窗
            this.setData({
              showBuildingModal: true
            });
          }
        } else {
          wx.showToast({
            title: res.result?.message || '获取页面信息失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('getSubProductPageInfo failed:', err);
        wx.showToast({
          title: '获取页面信息失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 选择楼栋
  onSelectBuilding(e) {
    const building = e.currentTarget.dataset.building;
    this.setData({
      curSelectedBuilding: building,
      showBuildingModal: false
    });

    // 缓存选中的楼栋（使用最新的服务器数据）
    wx.setStorageSync('curSelectedBuilding', {
      productId: this.data.productId,
      building: building
    });

    // 加载该楼栋的商品列表
    // 先加载该楼栋的购物车，再加载商品列表
    this.loadCartForCurrentBuilding();
    this.loadSubProductList();
  },

  // 加载楼栋商品列表
  loadSubProductList() {
    wx.showLoading({ title: '加载中' });
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getSubProductListForBuildingRequest: {
          productId: this.data.productId,
          buildingCode: this.data.curSelectedBuilding.buildingCode,
          schoolCode: this.data.schoolCode
        }
      },
      success: (res) => {
        console.log('getSubProductListForBuilding result:', res);
        if (res.result?.code === 200) {
          const subProductList = res.result.data.subProductList || [];
          const displayStockMap = this.computeDisplayStockMap(subProductList, this.data.shoppingCart);
          this.setData({
            subProductList,
            displayStockMap
          });
        } else {
          wx.showToast({
            title: res.result?.message || '获取商品列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('getSubProductListForBuilding failed:', err);
        wx.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 楼栋搜索
  onBuildingSearch(e) {
    const searchKey = e.detail.value.trim().toLowerCase();
    this.setData({
      buildingSearchKey: searchKey
    });

    if (!searchKey) {
      this.setData({
        filteredBuildings: this.data.subProductInitInfo.buildings || []
      });
      return;
    }

    const filteredBuildings = (this.data.subProductInitInfo.buildings || []).filter(
      building => building.buildingName.toLowerCase().includes(searchKey)
    );
    this.setData({
      filteredBuildings
    });
  },

  // 点击楼栋名称，重新选择楼栋
  onChangeBuildingClick() {
    this.setData({
      showBuildingModal: true,
      buildingSearchKey: '',
      filteredBuildings: this.data.subProductInitInfo.buildings || []
    });
  },

  // 关闭楼栋选择弹窗
  onCloseBuildingModal() {
    // 只有已经选择过楼栋才能关闭
    if (this.data.curSelectedBuilding) {
      this.setData({
        showBuildingModal: false,
        buildingSearchKey: '',
        filteredBuildings: this.data.subProductInitInfo.buildings || []
      });
    } else {
      wx.showToast({
        title: '请先选择楼栋',
        icon: 'none'
      });
    }
  },

  // 商品数量增加
  onProductIncrease(e) {
    const subProductId = e.currentTarget.dataset.id;
    const product = this.data.subProductList.find(p => p.subProductId === subProductId);
    
    if (!product) return;

    const shoppingCart = { ...this.data.shoppingCart };
    const currentCount = shoppingCart[subProductId]?.count || 0;
    
    // 检查库存
    if (currentCount >= product.stock) {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      });
      return;
    }

    if (!shoppingCart[subProductId]) {
      shoppingCart[subProductId] = {
        product: product,
        count: 0
      };
    }
    shoppingCart[subProductId].count++;

    this.updateShoppingCart(shoppingCart);
  },

  // 商品数量减少
  onProductDecrease(e) {
    const subProductId = e.currentTarget.dataset.id;
    const shoppingCart = { ...this.data.shoppingCart };

    if (!shoppingCart[subProductId] || shoppingCart[subProductId].count <= 0) {
      return;
    }

    shoppingCart[subProductId].count--;
    if (shoppingCart[subProductId].count === 0) {
      delete shoppingCart[subProductId];
    }

    this.updateShoppingCart(shoppingCart);
  },

  // 购物车商品数量增加
  onCartItemIncrease(e) {
    const subProductId = e.currentTarget.dataset.id;
    const shoppingCart = { ...this.data.shoppingCart };
    const product = shoppingCart[subProductId]?.product;

    if (!product) return;

    const currentCount = shoppingCart[subProductId].count;
    
    // 检查库存
    if (currentCount >= product.stock) {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      });
      return;
    }

    shoppingCart[subProductId].count++;
    this.updateShoppingCart(shoppingCart);
  },

  // 购物车商品数量减少
  onCartItemDecrease(e) {
    const subProductId = e.currentTarget.dataset.id;
    const shoppingCart = { ...this.data.shoppingCart };

    if (!shoppingCart[subProductId] || shoppingCart[subProductId].count <= 0) {
      return;
    }

    shoppingCart[subProductId].count--;
    if (shoppingCart[subProductId].count === 0) {
      delete shoppingCart[subProductId];
    }

    this.updateShoppingCart(shoppingCart);
  },

  // 更新购物车
  updateShoppingCart(shoppingCart) {
    let totalPrice = 0;
    let totalCount = 0;

    Object.keys(shoppingCart).forEach(key => {
      const item = shoppingCart[key];
      const price = parseFloat(item.product.price);
      const count = item.count;
      const itemTotal = price * count;
      
      // 为每个购物车项添加计算好的总价
      item.itemTotalPrice = itemTotal.toFixed(1);
      
      totalPrice += itemTotal;
      totalCount += count;
    });

    const displayStockMap = this.computeDisplayStockMap(this.data.subProductList, shoppingCart);

    this.setData({
      shoppingCart,
      totalPrice: totalPrice.toFixed(1),
      totalCount,
      displayStockMap
    });

    // 将当前楼栋的购物车写入本地存储，做到按楼栋隔离
    const key = this.getCartStorageKey();
    try {
      if (key) {
        wx.setStorageSync(key, shoppingCart);
      }
    } catch (e) {
      console.warn('write shopping cart storage failed', e);
    }
  },

  // 基于当前 productId + buildingCode 生成购物车存储键
  getCartStorageKey() {
    const productId = this.data?.productId;
    const buildingCode = this.data?.curSelectedBuilding?.buildingCode;
    if (!productId || !buildingCode) return '';
    return `cart_${productId}_${buildingCode}`;
  },

  // 加载当前楼栋的购物车并刷新 totals 与展示库存
  loadCartForCurrentBuilding() {
    const key = this.getCartStorageKey();
    if (!key) return;
    let storedCart = {};
    try {
      storedCart = wx.getStorageSync(key) || {};
    } catch (e) {
      console.warn('read shopping cart storage failed', e);
    }
    // 使用 updateShoppingCart 统一计算 totals 和展示库存
    this.updateShoppingCart(storedCart);
  },

  // 计算用于展示的库存（库存 - 已加入购物车的数量）
  computeDisplayStockMap(subProductList, shoppingCart) {
    const map = {};
    (subProductList || []).forEach(p => {
      const inCart = shoppingCart && shoppingCart[p.subProductId] ? shoppingCart[p.subProductId].count : 0;
      const remain = Math.max(0, Number(p.stock || 0) - Number(inCart || 0));
      map[p.subProductId] = remain;
    });
    return map;
  },

  // 获取商品在购物车中的数量
  getProductCount(subProductId) {
    return this.data.shoppingCart[subProductId]?.count || 0;
  },

  // 显示购物车弹窗
  onShowCartModal() {
    if (this.data.totalCount === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showCartModal: true
    });
  },

  // 关闭购物车弹窗
  onCloseCartModal() {
    this.setData({
      showCartModal: false
    });
  },

  // 防止弹窗内点击冒泡触发遮罩关闭
  noop() {},

  // 去下单
  onCheckout() {
    if (this.data.totalCount === 0) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      });
      return;
    }

    // TODO: 跳转到下单页面
    const cartItems = [];
    Object.keys(this.data.shoppingCart).forEach(key => {
      const item = this.data.shoppingCart[key];
      cartItems.push({
        subProductId: item.product.subProductId,
        productName: item.product.productName,
        price: item.product.price,
        count: item.count,
        imgUrl: item.product.imgList[0]
      });
    });

    const param = {
      productId: this.data.productId,
      buildingCode: this.data.curSelectedBuilding.buildingCode,
      buildingName: this.data.curSelectedBuilding.buildingName,
      cartItems: cartItems,
      totalPrice: this.data.totalPrice,
      totalCount: this.data.totalCount
    };

    wx.navigateTo({
      url: '/pages/snacksOrder/index?param=' + encodeURIComponent(JSON.stringify(param))
    });
  }
});

